package com.ruicar.afs.cloud.afscase.approvetask.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.afscase.approvetask.condition.ConsiderationCondition;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkProcessScheduleInfo;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPool;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPoolHistory;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkProcessScheduleInfoService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolHistoryService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.ApproveSubmitVO;
import com.ruicar.afs.cloud.afscase.processor.service.ReconsiderationWorkflowService;
import com.ruicar.afs.cloud.afscase.processor.vo.NormalTaskSubmitVO;
import com.ruicar.afs.cloud.afscase.reconsiderationprocess.entity.ApproveReconsiderationInfo;
import com.ruicar.afs.cloud.afscase.reconsiderationprocess.service.ReconsiderationProcessService;
import com.ruicar.afs.cloud.common.core.enums.AfsEnumUtil;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.ApproveTypeEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.RemainKeyEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.UseSceneEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @description: 复议申请
 * @author xiaolong
 * @version 1.0
 */
@Slf4j
@RestController
@AllArgsConstructor
@Api("复议申请")
@RequestMapping("/reconsideration")
public class ReconsiderationController {
    private ReconsiderationProcessService reconsiderationProcessService;
    private WorkProcessScheduleInfoService workProcessScheduleInfoService;
    private ReconsiderationWorkflowService workflowService;
    private WorkTaskPoolHistoryService workTaskPoolHistoryService;
    private WorkTaskPoolService workTaskPoolService;

    @PostMapping("/queryReconReason")
    @ApiOperation("复议理由查询")
    public IResponse<ApproveReconsiderationInfo> queryReconReason(@RequestBody ConsiderationCondition considerationCondition){
        ApproveReconsiderationInfo approveReconsiderationInfo = reconsiderationProcessService.getOne(Wrappers.<ApproveReconsiderationInfo>query().lambda()
        .eq(ApproveReconsiderationInfo::getApplyNo,considerationCondition.getApplyNo())
        .eq(ApproveReconsiderationInfo::getStageId,considerationCondition.getStageId()));
         return IResponse.success(approveReconsiderationInfo);

    }

    @PostMapping("/submitApprove")
    @ApiOperation("复议申请提交")
    public IResponse submitApprove(@RequestBody ApproveSubmitVO approveSubmitVO) {
        CaseApproveRecord caseApproveRecord = approveSubmitVO.getApproveRecord();
        WorkProcessScheduleInfo info = workProcessScheduleInfoService.getById(caseApproveRecord.getStageId());
        caseApproveRecord.setUseScene(UseSceneEnum.RECONSIDER.getValue());
        caseApproveRecord.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        workflowService.submit(NormalTaskSubmitVO.builder().record(caseApproveRecord).workFlowInfo(info).build());
        return IResponse.success("提交成功");
    }

    @PostMapping("/saveReturnReason")
    @ApiOperation("退回原因保存")
    @Transactional
        public IResponse saveReturnReason(@RequestBody CaseApproveRecord caseApproveRecord) {
        WorkProcessScheduleInfo info = workProcessScheduleInfoService.getById(caseApproveRecord.getStageId());
        caseApproveRecord.setUseScene(UseSceneEnum.RECONSIDER.getValue());
        caseApproveRecord.setApproveType(ApproveTypeEnum.PROCESS.getValue());
        workflowService.submit(NormalTaskSubmitVO.builder().record(caseApproveRecord).workFlowInfo(info).build());
        return IResponse.success("提交成功");
    }

    @PostMapping("/queryReturnRemind")
    @ApiOperation("查询部长退回理由")
    @Transactional
    public IResponse<List<CaseApproveRecord>> queryReturnRemind(@RequestBody CaseApproveRecord caseApproveRecord) {
        List<CaseApproveRecord> recordList = new ArrayList<>();
        CaseApproveRecord record = new CaseApproveRecord();

        WorkProcessScheduleInfo workProcessScheduleInfo = workProcessScheduleInfoService.getOne(Wrappers.<WorkProcessScheduleInfo>lambdaQuery()
                    .eq(WorkProcessScheduleInfo::getId,caseApproveRecord.getStageId()));
        if (ObjectUtils.isNotEmpty(workProcessScheduleInfo)) {
            List<WorkTaskPoolHistory> workTaskPoolHistoryList = workTaskPoolHistoryService.queryAllData(caseApproveRecord.getApplyNo(),
                    caseApproveRecord.getStageId(),
                    workProcessScheduleInfo.getCurrentNodeId());

            if (workTaskPoolHistoryList != null) {
                for (WorkTaskPoolHistory workTaskPoolHistory : workTaskPoolHistoryList) {
                    String remainDataStr = workTaskPoolHistory.getRemainData();
                    if (StringUtils.isNotBlank(remainDataStr)) {
                        JSONObject remainJson = JSONObject.parseObject(remainDataStr);
                        if (remainJson.containsKey(AfsEnumUtil.key(RemainKeyEnum.RECORD))) {
                            record = JSONObject.parseObject(remainJson.get(AfsEnumUtil.key(RemainKeyEnum.RECORD)).toString(), CaseApproveRecord.class);
                        }
                        recordList.add(record);
                    }
                }
            }
        }
        return IResponse.success(recordList);
    }

    @PostMapping("/findReturnRemind")
    @Transactional
    public IResponse<List<CaseApproveRecord>> findReturnRemind(@RequestBody CaseApproveRecord caseApproveRecord) {
        List<CaseApproveRecord> recordList = new ArrayList<>();
        CaseApproveRecord record = new CaseApproveRecord();

        WorkProcessScheduleInfo workProcessScheduleInfo = workProcessScheduleInfoService.getOne(Wrappers.<WorkProcessScheduleInfo>lambdaQuery()
                .eq(WorkProcessScheduleInfo::getId,caseApproveRecord.getStageId()));
        if (ObjectUtils.isNotEmpty(workProcessScheduleInfo)) {
            List<WorkTaskPoolHistory> workTaskPoolHistoryList = workTaskPoolHistoryService.findAllData(caseApproveRecord.getApplyNo(),
                    caseApproveRecord.getStageId(),
                    workProcessScheduleInfo.getCurrentNodeId());

            if (workTaskPoolHistoryList != null) {
                for (WorkTaskPoolHistory workTaskPoolHistory : workTaskPoolHistoryList) {
                    String remainDataStr = workTaskPoolHistory.getRemainData();
                    if (StringUtils.isNotBlank(remainDataStr)) {
                        JSONObject remainJson = JSONObject.parseObject(remainDataStr);
                        if (remainJson.containsKey(AfsEnumUtil.key(RemainKeyEnum.RECORD))) {
                            record = JSONObject.parseObject(remainJson.get(AfsEnumUtil.key(RemainKeyEnum.RECORD)).toString(), CaseApproveRecord.class);
                        }
                        recordList.add(record);
                    }
                }
            }
        }
        return IResponse.success(recordList);
    }

    @PostMapping("/queryReconsiderStatus")
    @ApiOperation("查询复议申请案件在复议申请表中的状态")
    @Transactional
    public IResponse<String> queryReconsiderStatus(@RequestBody CaseApproveRecord caseApproveRecord) {
        String businessStateIn = null;
        ApproveReconsiderationInfo reconsiderationInfo = reconsiderationProcessService.getOne(Wrappers.<ApproveReconsiderationInfo>lambdaQuery()
            .eq(ApproveReconsiderationInfo::getApplyNo,caseApproveRecord.getApplyNo())
            .eq(ApproveReconsiderationInfo::getStageId,caseApproveRecord.getStageId()));
        if (ObjectUtils.isNotEmpty(reconsiderationInfo)) {
            businessStateIn = reconsiderationInfo.getStatus();
        }
        return IResponse.success(businessStateIn);
    }

}